package com.shishuo.cms.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.Topic;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.api.weibo.Weibo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.GeneralResultBean;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.javabeans.weibo.WeiboBean;
import com.qq.connect.oauth.Oauth;
import com.qq.connect.utils.QQConnectConfig;
import com.shishuo.cms.constant.UserConstant;
import com.shishuo.cms.entity.UserEntity;
import com.shishuo.cms.service.UserService;
import com.shishuo.cms.util.HttpUtil;
import com.sun.jndi.url.corbaname.corbanameURLContextFactory;
import com.sun.org.apache.bcel.internal.generic.NEW;

@Controller
public class IndexAction extends IndexBaseAction {
	
	private static String accessToken = null;
	private static long tokenExpireIn = 0;;
	private static Date lastGetTokenTime = new Date();

	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public String index(HttpServletRequest request) throws Exception {
		String doMainUrl = request.getServerName();
		if (doMainUrl != null && !doMainUrl.equals("")
				&& doMainUrl.indexOf("localhost") == -1
				&& doMainUrl.indexOf("127.0.0.1") == -1) {
			String[] arrStrings = doMainUrl.split("\\.");
			String domainName = arrStrings[0];
			if (domainName.contains("goods_item_")) {
				return "forward:/goods_item/"
						+ domainName.replace("goods_item_", "") + ".htm";
			}
		}
		request.setAttribute("title", this.getMsgByMsgKey("main.title"));
		// 判断是否已登录
		if (!userIsLogined()) {
			loginByQQ(request);
		} else {
			// 参数中包含code
			if (request.getParameter("code") != null) {
				// 说明这个是绑定用户的。
				HttpSession session = request.getSession();
				UserEntity userEntity = (UserEntity) session
						.getAttribute(UserConstant.SESSION_USER);
				bandByQQ(request,userEntity);
			}
		}
		return this.getTemplatePath() + "index";
	}

	private String getAccessToken() {
		AccessToken accessTokenObj;
		try {
			Date nowDate = new Date();
			long diff = (nowDate.getTime() - lastGetTokenTime.getTime()) / 1000;// 当前时间与获取最后一次token的时差，单位秒
			if (null != accessToken && (diff < tokenExpireIn)) {
				return accessToken;
			}
			accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
			String accessTokenTemp = null, openID = null;
			if (accessTokenObj.getAccessToken().equals("")) {
				System.out.print("没有获取到响应参数");
			} else {
				accessTokenTemp = accessTokenObj.getAccessToken();
				tokenExpireIn = accessTokenObj.getExpireIn();
				lastGetTokenTime = new Date();
			}
			accessToken = accessTokenTemp;
			return accessToken;
		} catch (QQConnectException e) {
			e.printStackTrace();
		}
		return null;
	}

	private void loginByQQ(HttpServletRequest request)
			throws QQConnectException, Exception {
		accessToken = getAccessToken();
		if (accessToken != null) {
			// 利用获取到的accessToken 去获取当前用的openid -------- start
			OpenID openIDObj = new OpenID(accessToken);
			String openID = openIDObj.getUserOpenID();
			UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
			UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
			if (userInfoBean.getRet() == 0) {
				UserEntity userEntityRet = null;
				if (userService.existUserByOpenID(openID)) {
					userEntityRet = userService.getByQqOpenId(openID);
				} else {
					String user_img_url=HttpUtil.sendGet("https://graph.qq.com/user/get_user_info", getAppId(), accessToken, openID);
					userEntityRet = userService.addByOpenID(openID,
							userInfoBean.getNickname(), user_img_url);
				}
				HttpSession session = request.getSession();
				userEntityRet.setPassWord("");
				session.setAttribute(UserConstant.SESSION_USER, userEntityRet);
				//用户登录成功，自动发布一篇说说
				sendShuoShuoToQQ(openID,accessToken);
			} else {
				// out.println("很抱歉，我们没能正确获取到您的信息，原因是： " +
				// userInfoBean.getMsg());
			}
		}
	}
	private void sendShuoShuoToQQ(String openID, String accessToken) {
		Weibo weibo=new Weibo(accessToken, openID);
		Topic topic = new Topic(accessToken, openID);
        try {
        	WeiboBean weiboBean=weibo.addWeibo(getLoginShuoShuoContent());
        	if (weiboBean.getRet()==0) {
        		logger.info("您的微博已发表成功，请登录Qzone查看");
			}else {
				logger.info("很遗憾的通知您，发表微博失败！原因： " + weiboBean.getMsg());
			}
            GeneralResultBean grb = topic.addTopic(getLoginShuoShuoContent());
            if (grb.getRet() == 0) {
            	logger.info("您的说说已发表成功，请登录Qzone查看");
            } else {
            	logger.info("很遗憾的通知您，发表说说失败！原因： " + grb.getMsg());
            }
        } catch (QQConnectException e) {
            logger.error("抛异常了？");
        }
	}

	private String getLoginShuoShuoContent() {
		return "我已经成功注册A5Q6购物返现网,快来看看，不仅购物能返现还能得到长期分红，网址：http://www.a5q6.com ";
	}

	// 绑定QQ
	private void bandByQQ(HttpServletRequest request, UserEntity userEntityRet)
			throws QQConnectException, Exception {
		accessToken = getAccessToken();
		if (accessToken != null) {
			// 利用获取到的accessToken 去获取当前用的openid -------- start
			OpenID openIDObj = new OpenID(accessToken);
			String openID = openIDObj.getUserOpenID();
			UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
			UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
			if (userInfoBean.getRet() == 0&&(!openID.equals(userEntityRet.getQqOpenId()))) {
				String user_img_url=HttpUtil.sendGet("https://graph.qq.com/user/get_user_info", getAppId(), accessToken, openID);
				userEntityRet = userService.updateUserByOpenID(userEntityRet.getId(),openID,
						userInfoBean.getNickname(),user_img_url);
				HttpSession session = request.getSession();
				userEntityRet.setPassWord("");
				session.setAttribute(UserConstant.SESSION_USER, userEntityRet);
				//用户登录成功，自动发布一篇说说
				sendShuoShuoToQQ(openID,accessToken);
			} else {
				// out.println("很抱歉，我们没能正确获取到您的信息，原因是： " +
				// userInfoBean.getMsg());
			}
			
		}
	}
	private static String getAppId() {
		return QQConnectConfig.getValue("app_ID");
	}
	private boolean userIsLogined() {
		HttpSession session = request.getSession();
		UserEntity userEntity = (UserEntity) session
				.getAttribute(UserConstant.SESSION_USER);
		return (userEntity != null);
	}
}
